package com.linkdood.app.web.rest;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linkdood.app.annotation.Patch;
import com.linkdood.app.annotation.PatchRequestBody;
import com.linkdood.app.constants.ErrorCode;
import com.linkdood.app.constants.MenuCode;
import com.linkdood.app.domain.Authority;
import com.linkdood.app.domain.CustomRole;
import com.linkdood.app.exception.GeneralException;
import com.linkdood.app.service.AuthorityService;
import com.linkdood.app.service.CustomRoleService;
import com.linkdood.app.service.SysRoleMenuService;
import com.linkdood.app.utils.PaginationUtil;
import com.linkdood.app.utils.ResourceUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;


/**
 * 自定义角色
 *
 * @author hycao
 */

@Api(value = "自定义角色接口", tags = {"自定义角色接口"})
@Slf4j
@RestController
@RequestMapping("/api/custom-roles")
public class CustomRoleResource {
    private final SysRoleMenuService sysRoleMenuService;
    private final AuthorityService authorityService;
    private final CustomRoleService customRoleService;

    public CustomRoleResource(CustomRoleService customRoleService, AuthorityService authorityService,
                              SysRoleMenuService sysRoleMenuService) {
        this.customRoleService = customRoleService;
        this.authorityService = authorityService;
        this.sysRoleMenuService = sysRoleMenuService;
    }

    /**
     * 查询列表
     */
    @PreAuthorize("@ss.hasPermi('bxy:manager:index','bxy:user:index')")
    @GetMapping
    public ResponseEntity<?> getCustomRolePage(@RequestParam(value = "roleName", required = false) String roleName, Pageable pageable) {
        Page<CustomRole> page = customRoleService.pageCustomRoleByRoleNames(roleName, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page);
        return new ResponseEntity<>(page.getRecords(), headers, HttpStatus.OK);
    }

    /**
     * 获取指定 id 角色
     */
    @GetMapping("/{id}")
    public ResponseEntity<CustomRole> getCustomRole(@PathVariable String id) {
        CustomRole customRole = customRoleService.getById(id);
        return ResponseEntity.ok(customRole);
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('bxy:manager:add')")
    @PostMapping
    public ResponseEntity<CustomRole> createCustomRole(@RequestBody CustomRole customRole) {
        Optional<CustomRole> oldCustomRole = customRoleService.getCustomRoleByName(customRole.getName());
        if (oldCustomRole.isPresent()) {
            throw new GeneralException(ErrorCode.ERROR_CUSTOM_ROLE_EXISTED);
        }
        customRoleService.save(customRole);
        // 将角色与菜单权限  新增加到 角色与权限表
        customRoleService.saveRoleMenu(customRole);
        return ResponseEntity.ok(customRole);
    }

    /**
     * 更新角色
     */
    @PreAuthorize("@ss.hasPermi('bxy:manager:edit')")
    @PatchMapping("/{id}")
    @Patch(service = CustomRoleService.class)
    public ResponseEntity<CustomRole> updateCustomRole(@PathVariable String id, @PatchRequestBody CustomRole customRole) {
        customRoleService.updateById(customRole);
        // 更新权限角色表，先删除，重新添加
        sysRoleMenuService.removeById(customRole.getId());
        customRoleService.saveRoleMenu(customRole);
        return ResponseEntity.ok(customRole);
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('bxy:manager:delete')")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteCustomRole(@PathVariable String id) {
        Integer count = authorityService.countByRoleId(id);
        if (count != 0) {
            throw new GeneralException(MenuCode.NO_ROLE);
        }
        customRoleService.removeById(id);
        // 删除权限角色关联表
        sysRoleMenuService.removeById(id);
        return ResponseEntity.ok(ResourceUtil.success());
    }

}
